package cc.sunni.bootredis2.controller;

import cc.sunni.bootredis2.mapper.GoodsMapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GoodsController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private GoodsMapper goodsMapper;
    @Value("${server.port}")
    private String port;

    @Autowired
    private RedissonClient redisson;

    public static final String LOCK_PRE = "sunni";

    @GetMapping("/buy")
    public String buy() {
        RLock lock = redisson.getLock(LOCK_PRE);
        lock.lock();

        try {
            String result = redisTemplate.opsForValue().get("goods:001");
            int goodsCount = result == null ? 0 : Integer.parseInt(result);

            if (goodsCount > 0) {
                int stock = goodsCount - 1;
                redisTemplate.opsForValue().set("goods:001", String.valueOf(stock));
                System.out.println("端口:" + port + "买到商品,库存=" + stock);
                return "端口:" + port + "买到商品,库存=" + stock;
            } else {
                System.out.println("端口:" + port + "商品售罄");
                return "端口:" + port + "商品售罄";
            }
        } finally {
            // 判断锁状态
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    @GetMapping("/sell")
    public String sell(@RequestParam Integer id, @RequestParam Integer count) {
        return goodsMapper.decr(id, count) > 0 ? "success" : "fail";
    }

}
